import React from 'react';
import { Card, Button, Space, Divider, Input } from 'antd';
import { useDraggable } from '@dnd-kit/core'; // 引入 useDraggable
import { 
  BgColorsOutlined, 
  FormOutlined, 
  TableOutlined, 
  PictureOutlined,
  ContainerOutlined,
  BarChartOutlined,
  FileTextOutlined,
  SearchOutlined
} from '@ant-design/icons';

// 组件库定义
const COMPONENT_LIBRARY = {
  basic: [
    {
      type: 'text',
      label: '文本',
      icon: <FileTextOutlined />,
      defaultProps: { content: '文本内容' },
      defaultStyle: { fontSize: 14, color: '#333' }
    },
    {
      type: 'image',
      label: '图片',
      icon: <PictureOutlined />,
      defaultProps: { src: 'https://via.placeholder.com/200x150', alt: '图片' },
      defaultStyle: { width: 200, height: 150 }
    },
    {
      type: 'button',
      label: '按钮',
      icon: <BgColorsOutlined />,
      defaultProps: { text: '按钮', type: 'primary' },
      defaultStyle: { width: 'auto' }
    },
    {
      type: 'divider',
      label: '分割线',
      icon: <Divider />,
      defaultProps: { type: 'horizontal' },
      defaultStyle: { margin: '16px 0' }
    }
  ],
  form: [
    {
      type: 'input',
      label: '输入框',
      icon: <FormOutlined />,
      defaultProps: { placeholder: '请输入', type: 'text' },
      defaultStyle: { width: 200 }
    },
    {
      type: 'textarea',
      label: '文本域',
      icon: <FormOutlined />,
      defaultProps: { placeholder: '请输入', rows: 4 },
      defaultStyle: { width: 300 }
    },
    {
      type: 'select',
      label: '下拉选择',
      icon: <FormOutlined />,
      defaultProps: { 
        placeholder: '请选择',
        options: [
          { value: 'option1', label: '选项1' },
          { value: 'option2', label: '选项2' }
        ]
      },
      defaultStyle: { width: 200 }
    },
    {
      type: 'checkbox',
      label: '复选框',
      icon: <FormOutlined />,
      defaultProps: { text: '复选框', checked: false },
      defaultStyle: {}
    },
    {
      type: 'radio',
      label: '单选框',
      icon: <FormOutlined />,
      defaultProps: { text: '单选框', checked: false },
      defaultStyle: {}
    },
    {
      type: 'switch',
      label: '开关',
      icon: <FormOutlined />,
      defaultProps: { checked: false },
      defaultStyle: {}
    },
    {
      type: 'datepicker',
      label: '日期选择',
      icon: <FormOutlined />,
      defaultProps: { placeholder: '请选择日期' },
      defaultStyle: { width: 200 }
    }
  ],
  layout: [
    {
      type: 'container',
      label: '容器',
      icon: <ContainerOutlined />,
      defaultProps: { direction: 'vertical' },
      defaultStyle: { 
        padding: 16, 
        border: '1px dashed #d9d9d9', 
        borderRadius: 6,
        minHeight: 100
      }
    },
    {
      type: 'row',
      label: '行',
      icon: <ContainerOutlined />,
      defaultProps: { gutter: 16 },
      defaultStyle: { display: 'flex', marginBottom: 16 }
    },
    {
      type: 'col',
      label: '列',
      icon: <ContainerOutlined />,
      defaultProps: { span: 12 },
      defaultStyle: { flex: 1, padding: '0 8px' }
    }
  ],
  data: [
    {
      type: 'table',
      label: '表格',
      icon: <TableOutlined />,
      defaultProps: { 
        columns: [
          { title: '姓名', dataIndex: 'name' },
          { title: '年龄', dataIndex: 'age' }
        ],
        dataSource: [
          { name: '张三', age: 25 },
          { name: '李四', age: 30 }
        ]
      },
      defaultStyle: { width: '100%' }
    },
    {
      type: 'chart',
      label: '图表',
      icon: <BarChartOutlined />,
      defaultProps: { type: 'bar', data: [] },
      defaultStyle: { width: 400, height: 300 }
    }
  ]
};

export default function ComponentPanel({ onAddComponent }) {
  const [searchText, setSearchText] = React.useState('');

  // 过滤组件
  const filteredComponents = React.useMemo(() => {
    if (!searchText) return COMPONENT_LIBRARY;
    
    const filtered = {};
    Object.keys(COMPONENT_LIBRARY).forEach(category => {
      filtered[category] = COMPONENT_LIBRARY[category].filter(comp => 
        comp.label.toLowerCase().includes(searchText.toLowerCase())
      );
    });
    return filtered;
  }, [searchText]);

  // 不需要这里的 handleAddComponent，拖拽后在 DesignerPage 处理
  // const handleAddComponent = (component) => {
  //   onAddComponent(component);
  // };

  return (
    <div style={{ padding: 16, height: 'calc(100vh - 200px)', overflowY: 'auto' }}>
      {/* 搜索框 */}
      <Input
        placeholder="搜索组件..."
        prefix={<SearchOutlined />}
        value={searchText}
        onChange={(e) => setSearchText(e.target.value)}
        style={{ marginBottom: 16 }}
      />

      {/* 基础组件 */}
      <Card size="small" title="基础组件" style={{ marginBottom: 16 }}>
        <Space wrap>
          {filteredComponents.basic?.map((comp, index) => (
            <DraggableComponentButton 
              key={comp.type + index}
              component={comp}
              onAddComponent={onAddComponent}
            />
          ))}
        </Space>
      </Card>

      {/* 表单组件 */}
      <Card size="small" title="表单组件" style={{ marginBottom: 16 }}>
        <Space wrap>
          {filteredComponents.form?.map((comp, index) => (
            <DraggableComponentButton 
              key={comp.type + index}
              component={comp}
              onAddComponent={onAddComponent}
            />
          ))}
        </Space>
      </Card>

      {/* 布局组件 */}
      <Card size="small" title="布局组件" style={{ marginBottom: 16 }}>
        <Space wrap>
          {filteredComponents.layout?.map((comp, index) => (
            <DraggableComponentButton 
              key={comp.type + index}
              component={comp}
              onAddComponent={onAddComponent}
            />
          ))}
        </Space>
      </Card>

      {/* 数据展示组件 */}
      <Card size="small" title="数据展示组件" style={{ marginBottom: 16 }}>
        <Space wrap>
          {filteredComponents.data?.map((comp, index) => (
            <DraggableComponentButton 
              key={comp.type + index}
              component={comp}
              onAddComponent={onAddComponent}
            />
          ))}
        </Space>
      </Card>
    </div>
  );
}

// 独立的拖拽组件按钮
const DraggableComponentButton = ({ component, onAddComponent }) => {
  const { attributes, listeners, setNodeRef, transform } = useDraggable({
    id: `draggable-new-${component.type}-${Date.now()}`,
    data: { // 拖拽时携带组件的完整数据
      type: 'newComponent',
      componentData: component,
    },
  });

  const style = transform ? {
    transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
  } : undefined;

  return (
    <Button
      ref={setNodeRef}
      style={{ width: 80, height: 60, display: 'flex', flexDirection: 'column', alignItems: 'center', ...style }}
      {...listeners}
      {...attributes}
      onClick={() => onAddComponent && onAddComponent(component)} // 新增点击添加
    >
      {component.icon}
      <div style={{ fontSize: 12, marginTop: 4 }}>{component.label}</div>
    </Button>
  );
};